package com.fancy.learncenter.ui.fragment;


import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CartoonUnitBean;
import com.fancy.learncenter.bean.CartoonUnitListBean;
import com.fancy.learncenter.bean.CartoonWorkItemBean;
import com.fancy.learncenter.bean.CartoonWorkUnitBean;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.adapter.FinishedWorkAdapter;
import com.fancy.learncenter.ui.callback.AlbumImpl;
import com.fancy.learncenter.ui.view.CartoonUnitListPopu;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 已完成作业
 */
public class FinishedWorkFragment extends Fragment {


    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.unit_name)
    TextView unitNameText;
    @Bind(R.id.change_unit_arrow)
    ImageView changeUnitArrow;
    List<CartoonWorkItemBean> list = new ArrayList<>();
    FinishedWorkAdapter adapter;
    @Bind(R.id.unit_layout)
    RelativeLayout unitLayout;
    private List<CartoonUnitBean> unitList = new ArrayList<>();
    private CartoonUnitListPopu popu;
    private OnFinishWorkListener mListener;
    public FinishedWorkFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_finished_work, container, false);
        ButterKnife.bind(this, view);
        initView();

        getUnitList();
        return view;
    }


    @Override
    public void onResume() {
        super.onResume();

        getUnitItem("");
    }

    private void initView() {
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        adapter = new FinishedWorkAdapter(getActivity(), list);
        recyclerView.setAdapter(adapter);
        unitLayout.setEnabled(false);
        unitLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showPopu();

            }
        });
    }

    private void showPopu(){
        if (popu == null) {
            popu = new CartoonUnitListPopu(getActivity(), recyclerView, unitList);
            popu.showPopupWindow();
            popu.setListener(new AlbumImpl() {
                @Override
                public void onClick(int position) {

                    CartoonUnitBean bean = unitList.get(position);
                    String unitId = bean.getUnitId();
                    String unitName = bean.getUnitName();
                    unitNameText.setText(unitName);
                    getUnitItem(unitId);

                    popu.dismiss();

                }
            });
        }else {
            popu.showPopupWindow();
        }


    }


    /**
     * 获取单元列表
     */
    private void getUnitList(){

        Map<String,Object> map = new HashMap<>();
        map.put("classId", MyApplication.classIDStr);
        HttpMehtod.getInstance().cartoonGetUnitList(map, new CustomNetSubscriber(getActivity()) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CartoonUnitListBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonUnitListBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(),baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonUnitListBean>() {
                    @Override
                    public void success(CartoonUnitListBean dataBean) {

                        if (dataBean != null) {
                            CartoonUnitBean bean = new CartoonUnitBean();
                            bean.setUnitId("");
                            bean.setUnitName("全部");
                            unitList.add(bean);
                            unitList.addAll(dataBean.getResult());
                            unitLayout.setEnabled(true);
                        }
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }
        });

    }


    /**
     * 获取已完成的作业列表
     */
    private void getUnitItem(String unitId) {

        Map<String, Object> map = new HashMap<>();
        map.put("state", 1);
        map.put("classId", MyApplication.classIDStr);
        map.put("unitId",unitId);
        HttpMehtod.getInstance().cartoonListWork(map, new CustomNetSubscriber(getActivity()) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {


                //解析数据
                BaseBean<CartoonWorkUnitBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonWorkUnitBean.class);

                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);

                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonWorkUnitBean>() {
                    @Override
                    public void success(CartoonWorkUnitBean dataBean) {
                        if (dataBean != null) {
                            onButtonPressed(dataBean.getCount());
//                            list.clear();
//                            list.addAll(dataBean.getResult());
                            adapter.notifyDataSetChanged(dataBean.getResult());
                        }
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).dealData();
            }
        });

    }



    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(int finished) {
        if (mListener != null) {
            mListener.onFinishWork(finished);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFinishWorkListener) {
            mListener = (OnFinishWorkListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFinishWorkListener {
        // TODO: Update argument type and name
        void onFinishWork(int finished);
    }
}
